//
//  GoodsDetailCtr-购买.swift
//  smosky
//
//  Created by zhu xietong on 2018/5/22.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import soapp
import Eelay

open class ViticalButton: JoView {
    public let bt = UIButton()
    public let lable = UILabel()
    open override func addLayoutRules() {
        eelay = [
            [bt,[ee.X.Y,[0,-7]],"20",20],
            [lable,[bt,ee.B,ee.T,2],[ee.X]],
        ]
        bt.ui.padding(insets: [0])
    }
}


extension GoodsDetailCtr{
    
    open class BuyBar: EeBottomBar {
        open override var contentHeight: CGFloat{
            get{
                return 49
            }
        }
        
        public var specSelectorTask = SpecTask.default{
            didSet{
                buySelector.specTask = specSelectorTask
            }
        }
        
        
        public let buyBt = UIButton()
        public let careBt = ViticalButton()
        public let sellerBt = ViticalButton()
        public let cartBt = UIButton()
        
        open override func didLayoutRules() {
            
            sellerBt.bt.setImage( UIImage(named: "shop_store_gray"), for: .normal)
            sellerBt.bt.addTarget(self, action: #selector(seeSeller), for: .touchUpInside)
            careBt.bt.setImage(UIImage(named: "goods_save_n"), for: .normal)
            careBt.bt.setImage( UIImage(named:"goods_save_s")?.rt_tintedImage(with: ._tint), for: .selected)
            careBt.bt.addTarget(self, action: #selector(careToggle), for: .touchUpInside)
            
            sellerBt.lable.ui.cl_888.font10.center.text("店铺".loc)
            careBt.lable.ui.cl_888.font10.center.text("收藏".loc)
            buyBt.addTarget(self, action: #selector(toBuy), for: .touchUpInside)
            cartBt.addTarget(self, action: #selector(addCartAction), for: .touchUpInside)
        }
        
        public let line = UIView()
        public let line2 = UIView()
        
        open override func addLayoutRules() {

            contentView.eelay = [
                [sellerBt,[ee.L.Y,[10,0]],"40",44.co],
                [careBt,[sellerBt,ee.R,ee.L,10],[ee.Y],"40",44.co],
                [buyBt,[ee.T.R.B],94.co],
                [cartBt,[buyBt,ee.L,ee.R],[ee.T.B],94.co],
                [line,[ee.T.L.R],"\(TP.separatorHeight)"],
                [line2,[ee.L.B.R],"\(TP.separatorHeight)"]
            ]
            
           
            
            _ = buyBt.ui.font(size: 12).ncolor(hex: "#fff").ntitle(title: "立即购买".loc).padding(insets: [8,16])
            buyBt.setBackgroundImage(UIImage(named: "shop_buy"), for: .normal)
            
            _ = cartBt.ui.font(size: 12).ncolor(hex: "#fff").ntitle(title: "加入购物车".loc).buttonColor(color: ___shop.tint)
            line2.backgroundColor = UIColor._separator
            line.backgroundColor = ._separator
        }
        
        @objc open func seeSeller(){
//            let ctr =
            Goods.seeSeller(obj: DataNode.path(node: "merch", mo.model, value: NSMutableDictionary()), at: controller)
//            controller?.navigationController?.pushViewController(ctr, animated: true)
        }
        
        @objc open func addCartAction()
        {
            if mo.model["canAddCart",true.tag] == false.tag
            {
                "该[XX]不可加入购物车".replaceVars(values: OrderScheme.default.goodsTag).alert()
                return
            }
            
            buySelector.nextActions = [.加入购物车]
            showSpec()
        }
        
        
        func showSpec() {
            weak var wself = self
            EeAuthControl.getUser { (success, msg, user) in
                if success{
                    if let ws = wself
                    {
//                        co_delay(delay: 0.15) {
                        ws.controller?.present(ws.buySelector, animated: false, completion: nil)
//                        }
                    }
                }
            }
        }
        
        @objc open func toBuy(){
            buySelector.nextActions = [.购买]
            showSpec()

        }
        
        @objc open func buyAction() {
            
            showSpec()
            
//            self.controller?.present(buySelector, animated: false, completion: nil)
        }
        
        public var isCared:Bool{
            get{
                var cared = false
                if mo.model["isfavorite",false.tag] == true.tag
                {
                    cared = true
                }
                return cared
            }
        }
        
        override open func mo_model_reload() {
            careBt.bt.isSelected = isCared
            if isCared
            {
                careBt.lable.textColor = ._tint
            }
            else{
                careBt.lable.textColor = UIColor(shex: "#888")
            }
        }
        
        public func show() {
            
        }
        
        @objc open func careToggle() {
            weak var wself = self
            if JoUser.loginUser() == nil{
                JoAlertView(info: "提示".loc,"用户尚未登录，请先登录在进行相关操作".loc,"取消".loc).append(title: "立即登录".loc, style: .default, action: {
                    EeAuthControl.getUser(finish_block: { (_, _, _) in
                        
                    })
                }).show(at: wself?.controller)
                return
            }
            JoTask().post._surl(.商品收藏toggle).params(["id":mo.model["id",""]]).json_handle { (status, msg, obj, resp) in
                if status.isSuccess{
                    if let dict = obj as? NSMutableDictionary{
                        __post(notify: Goods.Notice.goodsCareStatusChange, object: nil, userInfo: nil)
                        wself?.mo.model["isfavorite"] = dict["isfavorite","0"]
                        wself?.mo_model_reload()
                        return
                    }
                }
                msg.alert()
                }.run()
            
        }
        
        
        
        
        var _buySelector:GoodsSepcSelectorCtr? = nil
        public lazy var buySelector:GoodsSepcSelectorCtr = { [unowned self] in
            if let ft = self._buySelector{
                return ft
            }
            
            weak var wself = self
            let ctr = GoodsSepcSelectorCtr()
            ctr.fromController = (mo.controller as? TypeInitController)

            weak var wctr = ctr
            ctr.nextAction = {
                values,nextType in

                switch nextType{
                case .加入购物车:
                    HUD.share.show().mode(.indeterminate)

                    JoTask().post.log.log_response()._surl(.加入购物车).params(values).json_handle { (status, msg, obj, resp) in
                        HUD.share.hide(animated: true)
                        if status.isSuccess{
                            if let dict = obj as? NSMutableDictionary{
                                __post(notify: Goods.Notice.goodsCartChage, object: nil, userInfo: nil)
                                "成功加入购物车".loc.alert()
                                wctr?.close()
                                return
                            }
                        }
                        msg.alert()
                        
                        
                        }.run()
                default:
                    wself?.optionConfirm(values: values, next: nextType)

                    co_delay(delay: 0.1, closure: {
                        ctr.close()
                    })
                }
                
            }
            
            self._buySelector = ctr
            let options = DataNode.path(node: "goodsoption", mo.model, value: NSMutableDictionary())
            ctr.mo.detail = mo.model.mutable_dictionary
            ctr.mo.model = options
            return ctr
        }()
        
        open func optionConfirm(values:[String:Any],next:SpecSelectorNext){
            switch next {
            case .购买,.预约:
                weak var wself = self
                co_delay(delay: 0.26) {
                    let submitCtr = SCOrderSubmitCtr()
                    submitCtr.buyType = .oneGoods(values)
                    wself?.controller?.navigationController?.pushViewController(submitCtr, animated: true)
                }
            default: break
                
            }
         
            
        }
        
    }
    
   
}




